<template>
  <div class="the-page">
    
  <div class="panel-search">
    
    <el-form ref="form" :model="listQuery" inline>
      <el-form-item label="版本号：">
        <el-input v-model="listQuery.version" clearable placeholder="请输入版本号进行查询" style="width: 200px;" class="filter-item" />
      </el-form-item>
      <el-form-item label="平台：">
        <el-select v-model="listQuery.osType" placeholder="请选中发布平台">
          <el-option v-for="item in platformList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="icon-search" @click.stop="filterHandle()">查询</el-button>
      </el-form-item>
    </el-form>
  </div>

  <div class="panel-table">
    <div class="table-head">
      <span>数据列表</span>
        <el-button v-if="hasPermission(['versions:publish'])" type="primary" icon="icon-plus" @click.stop="changeOSType('open')">发布版本</el-button>
    </div>
    
    <el-table :data="tableList" border style="width: 100%" :header-cell-style="{backgroundColor:'#ededed',padding:'12px 0'}" >
      <el-table-column prop="version" label="版本号" width="120"></el-table-column>
      <el-table-column prop="versionNumber" label="版本数字" width="100"> </el-table-column>
      <el-table-column prop="channel" label="渠道" width="120"> </el-table-column>
      <el-table-column prop="osType" label="平台" width="120"></el-table-column>

      <el-table-column prop="endpoint" label="业务端" width="120">
        <template #default="{row}">
          <span>{{{"PICO":" 品客"}[row.endpoint]||""}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="升级文案"></el-table-column>

      <el-table-column prop="mustUpgrade" label="是否必须升级" width="120">
        <template #default="{row}">
          <span>{{row.mustUpgrade ? '是' : '否'}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="downloadUrl" label="下载地址">
        <template #default="{row}">
          <a :href="row.downloadUrl" target="_blank" style="color: #1890ff;">{{row.downloadUrl}}</a>
        </template>
      </el-table-column>
      <el-table-column prop="operateName" label="操作人" width="140"></el-table-column>
      <el-table-column prop="createdAt" label="操作时间" width="180"></el-table-column>
    </el-table>

    <div class="table-pagination">
      
    <pagination :total="total" v-model:page="listQuery.page" v-model:limit="listQuery.pageSize" @pagination="getDataList" />
    </div>

  </div>




    <el-dialog title="发布版本" v-model="dialogVisible" :close-on-click-modal="false" width="700px">
      <el-form :model="addForm" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="平台：" prop="osType">
          <el-radio-group v-model="addForm.osType" @change="changeOSType">
            <el-radio label="ANDROID">ANDROID</el-radio>
            <el-radio label="IOS">IOS</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="强制更新：" prop="mustUpgrade">
          <el-radio-group v-model="addForm.mustUpgrade">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="版本号：" prop="version">
          <el-input v-model="addForm.version" placeholder="例：1.0.5，无需加v" style="width: 200px;" clearable class="customNumberInput"></el-input>
        </el-form-item>
        <el-form-item label="版本数字：" prop="versionNumber">
          <!-- <el-input v-model="addForm.versionNumber" placeholder="数字" style="width: 200px;" type="number" clearable></el-input> -->
          <el-input-number v-model="addForm.versionNumber" :min="1" :max="10000" label="数字" :precision="0"></el-input-number>
        </el-form-item>
        <el-form-item label="升级文案：" prop="remarks">
          <el-input v-model="addForm.remarks" placeholder="版本升级文案" type="textarea" show-word-limit maxlength="100" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="业务端：" prop="endpoint">
          <el-select v-model="addForm.endpoint" placeholder="请选择" disabled>
            <el-option v-for="item in endpointList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="addForm.osType == 'ANDROID'" label="发布渠道：" class="channelListItem" prop="channelData">
          <div v-for="(item, index) in addForm.channelData" :key="index" style="margin-bottom: 10px;" class="uploadItem">
            <div style="display: flex;">
              <el-select v-model="item.channel" placeholder="请选择" @change="changeDisabledChannel">
                <el-option v-for="item in channelList" :key="item.value" :label="item.label" :value="item.value" :disabled="item.isDisabled">
                </el-option>
              </el-select>
              <!-- <span style="margin-left: 10px; color: #1890ff; cursor: pointer;">
                点击上传{{addForm.osType == 'ANDROID' ? 'apk' : 'ipa'}}文件              
              </span> -->

              <el-upload v-if="item.fileName == ''" :http-request="Upload" :multiple="false" :limit="1" :before-upload="beforeAvatarUpload" action="">
                <span style="margin-left: 10px; color: #1890ff; cursor: pointer;" @click="handleClickUpload(index)">
                  点击上传{{addForm.osType == 'ANDROID' ? 'apk' : 'ipa'}}文件
                </span>
              </el-upload>
              <div v-else style="margin-left: 10px;" class="packageName" :title="item.fileName">
                {{item.fileName}}
                <i class="icon-close delPackage" @click="handleDeletePackage(index)"></i>
                <span style="display: inline-block; width:10px;"></span>
              </div>
            </div>

            <div class="delChannelItem">
              <el-button type="text" class="font-bold" @click="handleDeleteChennel(index)">
                <i class="icon-close"></i>
                <span>删除</span>
              </el-button>
            </div>
          </div>

          <div class="addChannel" :style="{'bottom': isUploading ? '42px' : '10px'}">
            <el-button type="text" class="font-bold" @click="addPublishChannel">+ 添加渠道</el-button>
          </div>
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmPublish">确定发布</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import { getVersionList, addVersion } from "@/api/config";
import { client } from "@/utils/alioss";
import { ElMessage,ElLoading } from 'element-plus'
export default {
  name: "ConfigPublishVersion",
  components: { Pagination },
  beforeRouteLeave(to, from, next) {
    // 点击浏览器的返回按钮时，关闭dialog
    this.dialogVisible = false;
    next();
  },
  data() {
    let checkChannel = (rule, value, callback) => {
      let nopass = false;
      value.forEach((item) => {
        if (item.channel == "" || item.downloadUrl == "") {
          // 渠道必选，文件也必须上传
          nopass = true;
        }
      });
      if (nopass && this.addForm.osType == "ANDROID") {
        callback(new Error("请先完善渠道信息"));
      } else {
        callback();
      }
    };
    let checkVersion = (rule, value, callback) => {
      let haveOther = false;
      for (let char of value) {
        if (isNaN(char) && char !== ".") {
          // 不是数字或者不是.
          haveOther = true;
        }
      }
      if (value.trim() == "") {
        callback(new Error("请输入版本号"));
      } else if (haveOther) {
        callback(new Error("请修改版本号格式"));
      } else {
        callback();
      }
    };
    return {
      listQuery: {
        version: "",
        osType: "",
        page: 1,
        pageSize: 10,
      },
      platformList: [
        { value: "", label: "全部" },
        { value: "ANDROID", label: "ANDROID" },
        { value: "IOS", label: "IOS" },
      ],
      tableList: [],
      total: 0,
      dialogVisible: false,
      addForm: {
        osType: "ANDROID", // 平台，默认Android
        mustUpgrade: "0", // 强制升级，默认否
        version: "", // 版本号
        versionNumber: null, // 版本数字
        remarks: "", // 升级文案
        endpoint: "PICO", // 业务端
        channelData: [
          { channel: "", downloadUrl: "", fileName: "" }
        ],
      },
      rules: {
        osType: [{ required: true }],
        mustUpgrade: [{ required: true }],
        // version: [ { required: true, message: '请输入版本号', trigger: 'blur' } ],
        version: [{ required: true, validator: checkVersion, trigger: "blur" }],
        versionNumber: [
          { required: true, message: "请输入版本数字", trigger: "blur" },
        ],
        remarks: [
          { required: true, message: "请输入版本升级文案", trigger: "blur" },
        ],
        endpoint: [
          { required: false, message: "请选择发布业务端", trigger: "blur" },
        ],
        channelData: [{ required: true, validator: checkChannel }],
      },
      channelList: [
        // 可以发布得渠道
        { value: "qumoyu", label: "qumoyu", isDisabled: false },
        { value: "yingyongbao", label: "yingyongbao", isDisabled: false },
        { value: "qihu360", label: "qihu360", isDisabled: false },
        { value: "baidu", label: "baidu", isDisabled: false },
        { value: "huawei", label: "huawei", isDisabled: false },
        { value: "xiaomi", label: "xiaomi", isDisabled: false },
        { value: "oppo", label: "oppo", isDisabled: false },
        { value: "vivostore", label: "vivostore", isDisabled: false },
        { value: "aliyingyong", label: "aliyingyong", isDisabled: false },
      ],
      endpointList: [
        // 可以发布得渠道
        { value: "QMY", label: "趣摸鱼" },
        { value: "GXD", label: "供销端" },
        { value: "PICO", label: " 品客" },
      ],
      isUploading: false, // 是否正在上传文件
    };
  },
  mounted() {
    this.getDataList();
  },
  methods: {
    filterHandle() {
      this.listQuery.page = 1;
      this.getDataList();
    },
    getDataList() {
      getVersionList({ ...this.listQuery }).then((res) => {
        this.tableList = res.data.items;
        this.total = res.data.pagination.total_record;
      });
    },
    changeOSType(e) {
      this.addForm = {
        osType: e == "open" ? "ANDROID" : e, // 平台，默认Android
        mustUpgrade: "0", // 强制升级，默认否
        version: "", // 版本号
        versionNumber: null, // 版本数字
        remarks: "", // 升级文案
        endpoint: "PICO", // 业务端
        channelData: [
          { channel: "", downloadUrl: "", fileName: "" }
        ],
      };
      if (e == "open") {
        // 打开dialog
        this.dialogVisible = true;
        this.channelList = this.channelList.map((em) => {
          // 重置发布渠道
            em.isDisabled = false;
          return em;
        });
        this.$nextTick(() => {
          this.$refs.ruleForm.clearValidate(); // 移除该表单项的校验结果
        });
        this.fileMapArr = [];
        this.uploadIndex = 0;
      }
    },
    handleDeletePackage(index) {
      this.addForm.channelData[index].downloadUrl = "";
      this.addForm.channelData[index].fileName = "";
    },
    handleDeleteChennel(index) {
      if (
        this.addForm.channelData.length == 1 &&
        this.addForm.osType == "ANDROID"
      ) {
        ElMessage.error("请至少保留一个发布渠道！");
        return false;
      }
      this.addForm.channelData.splice(index, 1);
      this.changeDisabledChannel();
    },
    addPublishChannel() {
      this.addForm.channelData.push({
        channel: "",
        downloadUrl: "",
        fileName: "",
      });
    },
    confirmPublish() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          addVersion(this.addForm).then((res) => {
            if (res.code === 0) {
              ElMessage({
                message: "发布成功",
                type: "success",
              });
              this.dialogVisible = false;
              this.listQuery.version = "";
              this.listQuery.osType = "";
              this.getDataList(); // 更新列表
            }
          });
        }
      });
    },

    handleClickUpload(index) {
      this.uploadIndex = index;
    },
    beforeAvatarUpload(file) {
      console.log("=====上传前", file);
      let getIndex = file.name.lastIndexOf(".");
      let getExtName = file.name.substr(getIndex + 1);
      if (getExtName !== "apk") {
        // 限制上传的文件格式
        ElMessage.error("只能上传apk文件");
        return false;
      }
      if (navigator.onLine) {
        this.loading =ElLoading.service({
          lock: true,
          text: "上传中...",
          spinner: "icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        this.isUploading = true;
        this.fileMapArr.push({ uid: file.uid, index: this.uploadIndex }); // 上传文件与操作渠道的映射关系
      } else {
        ElMessage({
          message: "网络开小差,上传失败",
          type: "warning",
        });
        return false;
      }
    },
    Upload(file) {
      var env = import.meta.env.VITE_APP_ENV;
      var fileName = `img/apk-${env}/${file.file.name}`;
      console.log(fileName);
      client()
        .put(fileName, file.file)
        .then((result) => {
          let operate_index = this.fileMapArr.find(
            (em) => em.uid == file.file.uid
          ).index;
          this.addForm.channelData[operate_index].fileName = file.file.name;
          this.addForm.channelData[operate_index].downloadUrl =
            "https://img.qumoyugo.com/" + result.name;
          this.isUploading = false;
          this.$refs.ruleForm.validateField("channelData"); // 只更新校验发布渠道
          this.loading.close();
        })
        .catch((err) => {
          console.log("err", err);
          this.loading.close();
        });
    },

    changeDisabledChannel() {
      // 已经选中的渠道禁用
      this.channelList.forEach((em) => {
        em.isDisabled = false;
        this.addForm.channelData.forEach((item) => {
          if (item.channel == em.value) {
            em.isDisabled = true;
          }
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/tablePage.scss";
.channelListItem {
  position: relative;
  .addChannel {
    position: absolute;
    bottom: 10px;
    right: 60px;
  }
  .uploadItem {
    display: flex;
    justify-content: space-between;
    .packageName {
      max-width: 210px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      position: relative;
      .delPackage {
        color: #ff4949;
        font-size: 16px;
        font-weight: bold;
        position: absolute;
        top: -2px;
        right: 0px;
        cursor: pointer;
      }
    }

    .delChannelItem {
      position: relative;
      right: 0px;
      i,
      span {
        color: #ff4949;
      }
      span {
        margin-left: -2px;
      }
    }
  }
}
</style>
